package codeRandomThoughts.Test99901背包;

import java.util.Scanner;

public class Solution {
    public static int testWeightBagProblem(int[] weight, int[] value, int bagSize) {
        //物品的数量
        int count = weight.length;

        //dp[i][j]代表编号为0~i的物品放入容量为j的背包的最大价值
        int[][] dp = new int[count][bagSize + 1];

        //初始化
        //dp[i][0]恒等于0,不用写代码,因为本来就是0
        //当j < weight[0]时,dp[0][j] = 0,也不用写代码
        //当j >= weight[0]时,dp[0][j] = value[0]
        for (int j = weight[0]; j < bagSize + 1; j++) {
            dp[0][j] = value[0];
        }

        //遍历
        for (int i = 1; i < weight.length; i++) {//遍历物品
            for (int j = 1; j <= bagSize; j++) {//遍历背包容量
                if (j < weight[i]) {//背包装不进去这个物品
                    dp[i][j] = dp[i - 1][j];
                } else {
                    dp[i][j] = Integer.max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]);
                }
            }
        }

        //打印dp数组看结果
        for (int i = 0; i < dp.length; i++) {
            for (int j = 0; j < dp[0].length; j++) {
                System.out.print(dp[i][j] + " ");
            }
            System.out.print("\n");
        }

        return dp[count - 1][bagSize];
    }

    public static void main(String[] args) {
        int[] weight = {1, 3, 4};
        int[] value = {15, 20, 30};
        int bagSize = 4;
        System.out.println(testWeightBagProblem(weight, value, bagSize));
    }
}
